import base64
import shutil    
import os

from werkzeug.utils import secure_filename

class FileService():
    def __init__(self):
        pass
    
    def parse( self, req_str):
        """ Parse input stream
        """
        info, data = req_str.split(',')
        _type, encoding = info.split(';')
        ftype, ext = _type.split(r'/')
        
        return {'encoding':encoding, 'type':ftype, 'ext':ext, 'data':data}

    def ajax_upload(self, req_str, file_name, folder):
        """ Save input stream into a file
        """
        info = self.parse(req_str)
        
        fname = secure_filename(file_name)
        
        fpath = r'./' + folder + r'/' + fname

        if self.exist(fname, folder):
            self.remove_file(fpath)
            f = open(fpath, 'wb' )
            f.write(base64.b64decode(info['data']))
            f.close()
        else:
            if not self.exist(fname, folder):
                self.make_dirs(r'./' + folder)
            f = open(fpath, 'wb' )
            f.write(base64.b64decode(info['data']))
            f.close()

        
    def exist(self, fname, folder):
        """ Check if a file under the company_name/item_id folder
        Arguments:
            fname -- file name
        """
        if fname is None:
            return False
        else:
            fpath = r'./' + folder + r'/' + fname
            return os.path.exists(fpath) and os.path.isfile(fpath) 

    def make_dirs(self, _path):
        """Arguments:
        path -- the relative path to current path
        Example: './l1/l2' or 'l1/l2'
        """
        if not os.path.exists(_path):
            os.makedirs(_path)
            return True
        return False
    
    def remove_dirs(self, _path):
        if os.path.isdir(_path):
            shutil.rmtree(_path)
    
    def get_dirs(self, fpath):
        """Get parent dirs
        """
        return os.path.dirname(fpath)
        
    def create_file(self, fpath):
        if not os.path.exists(fpath):
            f = open(fpath, 'w')
            f.close()
            return True
        return False
        
    def remove_file(self, fpath):
        """ If file exists and is a file
        """
        if os.path.isfile(fpath):
            os.remove(fpath)

